﻿using aier.dataaccess.dapper;
using aier.dataaccess.model;
using aier.xrm.wcf;
using log4net;
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace aier.business.logic
{
    public class ScreenCallBackBll
    {
        public CommonWcf communityWcf { get; set; }
        public ScreenCallBackDal screenCallBackDal { get; set; }

        public LeadDal leadDal { get; set; }

        public ScreenDal screenDal { get; set; }

        public ResResult resResult { get; set; }

        public CommonWcf commonWcf { get; set; }

        public ILog log { get; set; }



        public IEnumerable<ScreenCallBackView> GetScreenCallBacksByHospID(Guid accountId) {
            return screenCallBackDal.GetScreenCallBacksByHospID(accountId);
        }

        public ResResult UpdateScreenCallBacksDelay(Guid ownerId, ScreenCallBackModel screenCallBackModel,int delayDay)
        {
            var taskViewModel = screenCallBackDal.GetScreenNoticeData(screenCallBackModel.new_task.Value, ownerId);
            TaskInfo taskInfo = new TaskInfo();
            taskInfo.Description = screenCallBackModel.new_description;

            taskInfo.Activityid = screenCallBackModel.new_task.Value;

            DateTime taskStartData;

            if (DateTime.TryParse(taskViewModel.screenStartData, out taskStartData))
            {
              
                

                if (delayDay == 3)
                {
                    taskInfo.ScheduledStart = taskStartData.AddHours(8).AddDays(3);
                    taskInfo.ScheduledEnd = taskInfo.ScheduledStart.Value.AddDays(1);
                }
                else if (delayDay == 7)
                {
                    taskInfo.ScheduledStart = taskStartData.AddHours(8).AddDays(7);
                    taskInfo.ScheduledEnd = taskInfo.ScheduledStart.Value.AddDays(1);
                }
                else if (delayDay == 30)
                {
                    taskInfo.ScheduledStart = taskStartData.AddHours(8).AddMonths(1);
                    taskInfo.ScheduledEnd = taskInfo.ScheduledStart.Value.AddDays(1);
                }
                else if(delayDay == 0)
                {
                    if (screenCallBackModel.new_screencallbackid != Guid.Empty)
                    {
                        Entity screenCallBack = screenCallBackModel.AsCrmEntity();
                        commonWcf.UpdateEntityProxyById(ownerId, screenCallBack);
                    }
                    var taskEntityStatus = taskInfo.AsCrmEntity();
                    commonWcf.UpdateStateRequest(taskEntityStatus.Id, taskEntityStatus.LogicalName, 1, 5);
                    return resResult.SuccessResult();
                }

                if(screenCallBackModel.new_screencallbackid != Guid.Empty)
                {
                    Entity descCallBack = screenCallBackModel.AsCrmEntity();
                    CommonUtil.RemoveEntityAttributes(descCallBack, new string[] { "new_screencallbackid", "new_description" });
                    commonWcf.UpdateEntityProxyById(ownerId, descCallBack);
                }
                

                var taskEntity = taskInfo.AsCrmEntity();
                communityWcf.UpdateEntityProxyById(ownerId, taskEntity);
                return resResult.SuccessResult();
            }
            return resResult.FailResult("日期格式问题");
        }

        /// <summary>
        /// 根据任务ID与筛查宣教ID获取筛查回访结果
        /// </summary>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public ScreenCallBackView GetScreenCallBacksByID(Guid taskId, Guid screenId)
        {
            return screenCallBackDal.GetScreenCallBacksByID(taskId, screenId);
        }

        /// <summary>
        /// 回访详情中创建筛查回访
        /// </summary>
        /// <param name="screenCallBack">筛查回访视图</param>
        /// <returns></returns>
        public Guid CreateScreenCallBack(Guid ownerId, ScreenCallBackModel screenCallBack)
        {
            Entity entity = XrmSqlBuilderEx.AsCrmEntity<ScreenCallBackModel>(screenCallBack);
            Guid  callBackId = communityWcf.CreateEntityProxy(ownerId, entity);
            if (screenCallBack.new_contactresult == 100000000)
            {
                TaskInfo taskInfo = new TaskInfo();
                taskInfo.Activityid = screenCallBack.new_task.Value;
                var taskEntityStatus = taskInfo.AsCrmEntity();
                commonWcf.UpdateStateRequest(taskEntityStatus.Id, taskEntityStatus.LogicalName, 1, 5);
                if (screenCallBack.new_communicateresult == 100000000) {

                    Entity reservation = screenCallBack.reservation.AsCrmEntity();
                    
                    if (screenCallBack.new_screen != null) {
                        reservation["new_screen"] = new EntityReference("new_screen", (Guid)screenCallBack.new_screen);
                        if (!reservation.Contains("new_source"))
                        {
                            ScreenView screenView =  screenDal.FetchScreenByScreenID((Guid)screenCallBack.new_screen);
                            if (screenView.new_screentype == 100000000)
                            { //社区
                                reservation["new_source"] = new OptionSetValue(3);//社区筛查
                            }
                            else if (screenView.new_screentype == 100000001)
                            { //校园
                                reservation["new_source"] = new OptionSetValue(7);
                            }
                            else if (screenView.new_screentype == 100000002) //大学校园
                            {
                                reservation["new_source"] = new OptionSetValue(8);
                            }
                            else if (screenView.new_screentype == 100000003) {//大客户活动
                                reservation["new_source"] = new OptionSetValue(6);
                            }
                        }
                    }
                    
                    if (screenCallBack.new_lead!=null) {
                        //LeadBll leadBll = new LeadBll();
                        LeadView lead = leadDal.QueryLeadInfoById((Guid)screenCallBack.new_lead);
                        //if (lead.new_mobile != null) {
                        //    reservation["new_mobile"] = lead.new_mobile;
                        //}

                        //if (lead.Address1_Telephone1 != null) {
                        //    reservation["new_mobile"] = lead.Address1_Telephone1;
                        //}

                        if (lead.new_phone != null) {
                            reservation["new_mobile"] = lead.new_phone;
                        }

                        if (lead.new_age != null )
                        {
                            reservation["new_age"] = lead.new_age;
                        }
                        if (lead.new_gender != null )
                        {
                            reservation["new_gender"] = new OptionSetValue((int)lead.new_gender);
                        }

                        if (lead.new_wechat != null )
                        {
                            reservation["new_wechat"] = lead.new_wechat;
                        }
                        if (lead.new_qq != null )
                        {
                            reservation["new_qq"] = lead.new_qq;
                        }
                        if (lead.new_insuranceid != null )
                        {
                            reservation["new_insuranceid"] = lead.new_insuranceid;
                        }

                        if (lead.new_insurancetype != null)
                        {
                            reservation["new_insurancetype"] = new OptionSetValue((int)lead.new_insurancetype);
                        }


                    }
                    Guid targetid = commonWcf.CreateEntityProxy(ownerId, reservation);
                }
            }
            return callBackId;
        }

        /// <summary>
        /// 修改筛查回访信息
        /// </summary>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public ResResult UpdateScreenCallBacksData(Guid ownerId, ScreenCallBackModel screenCallBackModel)
        {
            if (screenCallBackModel.new_screencallbackid == Guid.Empty)
            {
                resResult = resResult.FailResult("没有筛查回访记录");
                return resResult;
            }
            if (!string.IsNullOrWhiteSpace(screenCallBackModel.new_description) 
                || screenCallBackModel.new_communicateresult != null 
                || screenCallBackModel.new_contactresult != null)
            {
                Entity callBackEntity = screenCallBackModel.AsCrmEntity();
                commonWcf.UpdateEntityProxyById(ownerId, callBackEntity);
                if(screenCallBackModel.new_contactresult == 100000000)
                {
                    TaskInfo taskInfo = new TaskInfo();
                    taskInfo.Activityid = screenCallBackModel.new_task.Value;
                    var taskEntityStatus = taskInfo.AsCrmEntity();
                    commonWcf.UpdateStateRequest(taskEntityStatus.Id, taskEntityStatus.LogicalName, 1, 5);
                    return resResult.SuccessResult();
                }
            }
            return resResult.SuccessResult();
        }

        /// <summary>
        /// 根据任务ID与筛查宣教ID获取筛查回访结果
        /// </summary>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public IEnumerable<dynamic> GetScreenCallBackByLeadId(Guid leadId)
        {
            return screenCallBackDal.GetScreenCallBackByLeadId(leadId);
        }
    }
}
